package com.yizhuoyan.his.serviceimpl.registrar;

import com.yizhuoyan.his.ao.ModifyRegistrationLevelAo;
import com.yizhuoyan.his.ao.RegistrationLevelAo;
import com.yizhuoyan.his.dao.HosRegistrationLevelDao;
import com.yizhuoyan.his.entity.HosRegistrationLevelEntity;
import com.yizhuoyan.his.exception.HISDataExistsException;
import com.yizhuoyan.his.exception.HISDataNotExistsException;
import com.yizhuoyan.his.exception.HISIllegalParameterException;
import com.yizhuoyan.his.service.registrar.RegistrationLevelService;
import com.yizhuoyan.his.servicesupport.DatabaseIdGenerateSupportService;
import com.yizhuoyan.his.util.AssertThrowUtil;
import com.yizhuoyan.his.util.BeanMap;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import javax.validation.constraints.NotNull;
import java.util.List;
import java.util.Objects;

@Slf4j
@Validated
@Transactional
@Service
public class RegistrationLevelServiceImpl implements RegistrationLevelService, AssertThrowUtil {
    @Autowired
    HosRegistrationLevelDao dao;
    @Autowired

    DatabaseIdGenerateSupportService idGenerateSupportService;

    @Override
    public HosRegistrationLevelEntity addRegistrationLevel(@NotNull RegistrationLevelAo ao) throws Exception {
        log.trace("添加挂号基本信息,参数为：{}", ao);
        String name = ao.getName();
        String code = ao.getCode();
        Integer fee = ao.getFee();
        Integer showOrder = ao.getShowOrder();
        Integer quota = ao.getQuota();
        if (dao.exists("code", code)) {
            log.trace("挂号级别编码{}已存在，不可以添加", code);
            throw new HISDataExistsException(String.format("挂号级别编码[%s]已存在", code));
        }
        log.trace("挂号级别编码{}不存在，可以添加", code);
        if (dao.exists("name", name)) {
            log.trace("挂号级别别名{}已存在，不可以添加", name);
            throw new HISDataExistsException(String.format("别名[%s]已存在", name));
        }
        log.trace("挂号级别别名{}不存在，可以添加", name);

        HosRegistrationLevelEntity e = new HosRegistrationLevelEntity();
        e.setFee(fee);
        e.setName(name);
        e.setQuota(quota);
        e.setCode(code);
        e.setShowOrder(showOrder);
        e.setId(idGenerateSupportService.nextId());
        dao.insert(e);
        log.trace("挂号级别信息添加成功{}", ao);
        return e;

    }


    @Override
    public void removeRegistrationLevel(Long id) throws Exception {
        // 1验证清理参数
        if (id == null) {
            throw new HISDataNotExistsException("id为null");
        }
        // 2业务逻辑
        // 2.1 依次删除
        dao.delete(id);


    }

    @Override
    public void removeRegistrationLevels(Long... ids) throws Exception {
        // 1验证清理参数
        // 1.1
        if (ids == null) {
            throw new NullPointerException("ids为null");
        }
        // 1.2 如果没有指定id
        if (ids.length == 0) {
            return;
        }
        // 2业务逻辑
        // 2.1 依次删除

        for (Long id : ids) {
            if (id != null) {
                // id值合法时才删除
                // 物理删除
                dao.delete(id);

            }
        }
    }

    @Override
    public void modifyRegistrationLevel(@NotNull Long id, @NotNull ModifyRegistrationLevelAo ao) throws Exception {
        //参数验证
        //业务逻辑
        HosRegistrationLevelEntity r = new HosRegistrationLevelEntity();
        HosRegistrationLevelEntity old = dao.selectById(id);
        if (old == null) {
            throw new HISDataNotExistsException(+id + "id所对应的值不存在");
        }
        BeanMap updateMap = BeanMap.of(4);
        String newCode = ao.getCode();
        log.trace("判断code是否需要修改");
        if (!Objects.equals(newCode, old.getCode())) {
            log.trace("code需要修改,判断新code是否已存在");
            if (dao.exists("code", newCode)) {
                log.trace("挂号编码{}已存在，不可以添加", newCode);
                throw new HISDataExistsException(String.format("编码[%s]已存在", newCode));
            }
            log.trace("newCode合法，需要修改");
            updateMap.append("code", newCode);
        }
        log.trace("判断挂号级别别名name是否需要修改");
        String newName = ao.getName();
        if (!Objects.equals(newName, old.getName())) {
            log.trace("newName合法，需要修改");
            updateMap.append("name", newName);
        }

        if (old.getShowOrder() != ao.getShowOrder()) {
            log.trace("showOrder顺序号合法，可以修改");
            updateMap.append("showOrder", ao.getShowOrder());
        }


        if (!updateMap.isEmpty()) {
            log.trace("执行更新，需要修改字段为{}", updateMap);
            dao.update(id, updateMap);
        }
    }

    @Override
    public HosRegistrationLevelEntity queryRegistrationLevelById(@NotNull Long id) throws Exception {
        HosRegistrationLevelEntity e = dao.selectById(id);
        if (e == null) {
            log.trace("未找到id[{}]对应记录直接返回null", id);
            return null;
        }
        return e;
    }

    @Override
    public List<HosRegistrationLevelEntity> queryRegistrationLevelAll(String key, String orderBy) throws Exception {
        log.debug("模糊查询挂号级别信息，key为：{}", key);

        if (key != null) {
            final int keyMaxChars = 10;
            assertLessThan("查询关键字", key, keyMaxChars);
            key = key + "%";
        }
        List<HosRegistrationLevelEntity> result = dao.selectAll("show_order asc");
        return result;

    }
}
